import React, {useEffect, useRef, useState} from "react";
import "./index.scss"; // 引入样式文件
import {ESGltfModel, ESImageLabel, type ESJVector2D} from "earthsdk3";
// @ts-ignore
import {ESObjectsManager, type ESSceneObject} from "earthsdk3";
import {ESUeViewer} from "earthsdk3-ue";
import {ESCesiumViewer} from "earthsdk3-cesium";

// 创建 ESObjectsManager 实例
const objm = new ESObjectsManager(ESUeViewer, ESCesiumViewer);
const BaseEvents: React.FC = () => {
    const imageryLayerRef = useRef<ESSceneObject | undefined>(undefined);
    const containerRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (!containerRef.current) return;

        // 创建 Cesium 视口
        const viewer = objm.createCesiumViewer(containerRef.current);
        console.log("viewer", viewer);
        // 通过json创建一个影像图层,加载全球影像切片
        const imageryLayer = objm.createSceneObjectFromJson({
            id: "9812a65f-0de0-4f7b-b234-809c0c2fb8ef",
            show: true,
            type: "ESImageryLayer",
            maximumLevel: 18,
            name: "全球影像",
            url: "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
        });
        imageryLayerRef.current = imageryLayer;

        //添加一个楼宇
        const model = objm.createSceneObject(ESGltfModel);
        model!.position = [116.404, 39.904, 0];
        // 允许被拾取开启(默认关闭状态)
        model!.allowPicking = true
        // 监听被点击事件pickedEvent
        model!.pickedEvent.don((e) => {
            // 信息返回
            console.log("被拾取信息", e)
            alert('我被点击了!')
        })
        //再添加一个楼
        const model2 = objm.createSceneObject(ESGltfModel);
        model2!.position = [116.404, 39.905, 0];
        // 添加一个图片标签？暂且这么称呼
        // 创建一个ESImageLabel对象,该对象拥有特殊鼠标事件widgetEvent
        /**
         * widgetEvent:鼠标事件
         *  返回信息:
         *      左键点击:{event:"leftClick"}
         *      右键点击:{event:"rightClick"}
         *      鼠标进入:{event:"mouseEnter"}
         *      鼠标移出:{event:"mouseLeave"}
         */
        const imageLabel = objm.createSceneObject(ESImageLabel);
        imageLabel!.position = [116.404, 39.903, 0];
        imageLabel!.allowPicking = true
        imageLabel!.widgetEvent.don((e) => {
            console.log("widgetEvent信息", e)
            switch (e.type) {
                case 'mouseEnter':
                    // alert("鼠标进入!")
                    break;
                case 'mouseLeave':
                    // alert("鼠标移出!")
                    break;
                case 'leftClick':
                    alert("被左键点击了!")
                    break;
                case 'rightClick':
                    alert("被右键点击了!")
                    break;
                default:
                    break;
            }

        })
        // 通过json创建一个影像图层
        // objm.json = {
        //   asset: {
        //     type: "ESObjectsManager",
        //     version: "0.1.0",
        //     createdTime: "2022-06-17T05:54:41.744Z",
        //     modifiedTime: "2025-03-06T06:28:28.970Z",
        //     name: "图层管理",
        //   },
        //   viewers: [
        //     {
        //       id: "b8fc803b-38f6-4f66-b4b9-abfbbbb56cea",
        //       type: "ESCesiumViewer",
        //       show: true,
        //       globeShow: true,
        //       ionAccessToken: "",
        //       apiKey: "",
        //       apiUrl: "",
        //       secretKey: "",
        //       speechVoiceMode: "",
        //       hoverTime: 2,
        //       debug: false,
        //       lonLatFormat: "DECIMAL_DEGREE",
        //       fov: 60,
        //       currentTime: 1741233600000,
        //       simulationTime: 1741190400000,
        //       timeSync: false,
        //       rain: 0,
        //       snow: 0,
        //       cloud: 0,
        //       fog: 0,
        //       depthOfField: 0,
        //       atmosphere: true,
        //       sun: true,
        //       moon: true,
        //       flyToBoundingSize: 256,
        //       editingHeightOffset: 0,
        //       terrainShader: {
        //         slope: {
        //           show: false,
        //         },
        //         aspect: {
        //           show: false,
        //         },
        //         elevationRamp: {
        //           show: false,
        //         },
        //         elevationContour: {
        //           show: false,
        //           color: [1, 0, 0, 1],
        //           spacing: 150,
        //           width: 2,
        //         },
        //       },
        //       name: "undefined_ined",
        //     },
        //   ],
        //   sceneTree: {
        //     root: {
        //       children: [
        //         {
        //           name: "新建场景",
        //           children: [
        //             {
        //               name: "全球影像",
        //               sceneObj: {
        //                 id: "ae103185-08c7-4ed0-b6d4-15ad77bbbf66",
        //                 type: "ESImageryLayer",
        //                 url: "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
        //                 rectangle: [-180, -90, 180, 90],
        //                 maximumLevel: 18,
        //                 name: "全球影像",
        //                 allowPicking: true,
        //               },
        //               children: [],
        //             },
        //           ],
        //         },
        //         {
        //           name: "相机图元",
        //           sceneObj: {
        //             id: "41c111c1-8c2b-45f2-921e-eb47c425c223",
        //             type: "ESImageLabel",
        //             position: [
        //               111.00436500071837, 27.11546611226795, -0.006209566152813388,
        //             ],
        //             name: "相机图元",
        //             renderMode: 4,
        //           },
        //           children: [],
        //         },
        //         {
        //           name: "坐标图元",
        //           sceneObj: {
        //             id: "057017c1-44bd-4889-8bdb-b78452522eb2",
        //             type: "ESPoi2D",
        //             position: [
        //               111.00396954350059, 27.10780338965234, -0.004921383584093101,
        //             ],
        //             name: "坐标图元",
        //             mode: "P3D04",
        //           },
        //           children: [],
        //         },
        //         {
        //           name: "警车",
        //           sceneObj: {
        //             id: "e60554b5-e528-4a1f-a879-56a5bfd526dc",
        //             type: "ESCar",
        //             collision: true,
        //             allowPicking: true,
        //             position: [
        //               111.00894908061393, 27.10301817015784, -0.007865467481739654,
        //             ],
        //             scale: [50, 50, 50],
        //             name: "警车",
        //           },
        //           children: [],
        //         },
        //         {
        //           name: "红色多边形",
        //           sceneObj: {
        //             id: "7a337857-8146-49f1-8f30-4b24e3f786d6",
        //             type: "ESGeoPolygon",
        //             name: "红色多边形",
        //             collision: true,
        //             allowPicking: true,
        //             fillStyle: {
        //               color: [1, 0, 0, 1],
        //               material: "",
        //               materialParams: {},
        //               ground: false,
        //             },
        //             points: [
        //               [
        //                 111.00681208893155, 27.109400712315814,
        //                 -0.0019432002352708561,
        //               ],
        //               [
        //                 111.00816322005096, 27.10594938028908,
        //                 -0.001952182496056232,
        //               ],
        //               [
        //                 111.01064844926147, 27.105055763299234,
        //                 -0.0036560132587008538,
        //               ],
        //               [111.01185522112183, 27.10582495506876, -0.00314488607858293],
        //               [
        //                 111.01012278358284, 27.10789110878672,
        //                 -0.0052334027690486284,
        //               ],
        //               [
        //                 111.00841719779696, 27.109215302127783,
        //                 -0.004173354738300087,
        //               ],
        //               [
        //                 111.00780390674721, 27.109695627919915,
        //                 -0.005438400734806566,
        //               ],
        //             ],
        //           },
        //           children: [],
        //         },
        //       ],
        //     },
        //   },
        //   viewCollection: [],
        //   lastView: {
        //     position: [111.01118339587974, 27.098201084210086, 395.6679243907117],
        //     rotation: [
        //       337.46537890827136, -24.123843663214064, 0.0007594981744258459,
        //     ],
        //   },
        // };
        // 监听视口创建完成事件
        objm.viewerCreatedEvent.don((viewer) => {
            //初始化视角-两栋楼宇
            viewer.flyIn(
                [116.39947309868032, 39.90592001431495, 334.38857241671485],
                [121.37477595297989, -33.67659827219708, 359.9997913701847],
                3,
            );
            //初始化视角-全局拾取（警车视角）
            // viewer.flyIn(
            //   [111.01118339587974, 27.098201084210086, 395.6679243907117],
            //   [337.46537890827136, -24.123843663214064, 0.0007594981744767348],
            //   3,
            // );
            /**
             *
             * pick(screenPosition, attachedInfo)：拾取方法
             *  参数1：screenPosition 像素点位置
             *  参数2：attachedInfo 附加信息，【可选，默认undefined】（场景对象pickedEvent被拾取的时候用来区分是哪些自定义事件触发的）
             *
             */
            // 鼠标单击click事件的时候,定义自定义的pick事件
            viewer.clickEvent.don((e) => {
                console.log("e", e);
                //自定义pick事件
                viewer
                    .pick(e.screenPosition as ESJVector2D, "customPickEvent")
                    .then((res) => {
                        // 全局拾取对象
                        console.log("拾取到的信息", res);
                        if (res && res.sceneObject) {
                            console.log("拾取到的es对象", res.sceneObject);
                        }
                    });
                //pickPosition拾取位置
                viewer.pickPosition(e.screenPosition as ESJVector2D).then(res => {
                    console.log("拾取到的坐标", res);
                })
            });
        });
    }, []);

    return (
        <div className="box">
            <div className="container" ref={containerRef}></div>
        </div>
    );
};

export default BaseEvents;
